// API请求封装
import request from "@/utils/request";
import { ElMessage } from "element-plus";
import { getToken, clearAuth, isTokenExpired } from "@/utils/auth";
import * as merchantApi from "./merchant"; // 导入 merchant.ts 中的所有导出

// ==================== 用户认证相关 ====================

// 登录
export async function login(data: { username: string; password: string }) {
  return request.post("/api/auth/login", data);
}

// 注册
export async function register(data: {
  username: string;
  password: string;
  phone: string;
  email: string;
}) {
  return request.post("/api/auth/register", data);
}

// 退出登录
export async function logout() {
  return request.post("/api/auth/logout");
}

// ==================== 用户信息相关 ====================

// 获取当前用户个人资料
export async function getUserProfile() {
  return request.get("/api/users/profile");
}

// 更新当前用户个人资料
export async function updateUserProfile(data: {
  username?: string;
  email?: string;
  avatar?: string;
}) {
  return request.put("/api/users/profile", data);
}

// 更新当前用户密码
export async function updateUserPassword(data: {
  oldPassword: string;
  newPassword: string;
}) {
  return request.put("/api/users/password", data);
}

// 上传用户头像
export async function uploadUserAvatar(formData: FormData) {
  return request.post("/api/users/avatar", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

// 删除url对应的图像
export async function deleteUserImage(imageUrl: string) {
  return request.delete("/api/users/images", { data: { url: imageUrl } });
}

// ==================== 资源管理 ====================

// 上传图片
export async function uploadImage(formData: FormData) {
  return request.post("/api/admin/resources", formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}

// 删除url对应的图像
export async function deleteImage(imageUrl: string) {
  return request.delete("/api/admin/resources", { data: { url: imageUrl } });
}

// ==================== 商家店铺相关 (从 merchant.ts 导入) ====================
export const {
  getMerchantStores,
  getStoreDetail,
  createStore,
  updateStore,
  updateStoreStatus,
  uploadStoreAvatar,
  deleteStoreAvatar,
  listPromotions,
  createPromotion,
  updatePromotion,
  deletePromotion,
  listFoods,
  createFood,
  getFoodByStoreIdAndFoodId,
  updateFood,
  deleteFood,
  updateFoodStatus,
  uploadFoodImage,
  deleteFoodImage,
  getCategories,
  addCategory,
  updateCategory,
  deleteCategory,
  getOrders,
  updateOrderStatus,
  getDetailOrders,
  listReviews,
  getStoreOrderStats,
  getStoreReviewStats,
  getStoreTopProducts,
} = merchantApi;

// 获取订单详情 (管理员)
export async function getOrderDetail(orderId: number) {
  return request.get(`/api/admin/orders/${orderId}`);
}

// 获取公开的店铺分类列表（不需要认证）
export async function getPublicStoreCategories() {
  return request.get("/api/categories");
}

// 添加店铺分类
export async function addStoreCategory(data: any) {
  return request.post("/api/admin/stores/category", data);
}

// 更新店铺分类
export async function updateStoreCategory(id: string, data: any) {
  return request.put(`/api/admin/stores/category/${id}`, data);
}

// 删除店铺分类
export async function deleteStoreCategory(id: string) {
  return request.delete(`/api/admin/stores/category/${id}`);
}

// ==================== 管理员用户管理 ====================

// 获取用户列表
export async function getUsers(params?: any) {
  console.log("调用getUsers API，参数:", params);
  try {
    const response = await request.get("/api/admin/users", { params });
    console.log("getUsers API响应:", response);
    return response;
  } catch (error) {
    console.error("getUsers API错误:", error);
    throw error;
  }
}

// 更改用户状态
export async function updateUserStatus(
  userId: string,
  status: string,
  reason?: string
) {
  console.log("调用updateUserStatus API，参数:", { userId, status, reason });
  try {
    const response = await request.put(`/api/admin/users/${userId}/status`, {
      status,
      reason: reason || (status === "SUSPENDED" ? "管理员禁用" : ""),
    });
    console.log("updateUserStatus API响应:", response);
    return response;
  } catch (error) {
    console.error("updateUserStatus API错误:", error);
    throw error;
  }
}

// ==================== 管理员商家管理 ====================

// 获取商家列表
export async function getMerchants(params?: any) {
  console.log("调用getMerchants API，参数:", params);
  try {
    // 首先获取店铺分类列表
    let categories: Record<string, string> = {};
    try {
      const categoriesRes = await getPublicStoreCategories();
      if (categoriesRes.data && Array.isArray(categoriesRes.data)) {
        categoriesRes.data.forEach((cat: any) => {
          if (cat.id && cat.name) {
            categories[cat.id] = cat.name;
          }
        });
      }
      console.log("获取到的店铺分类:", categories);
    } catch (error) {
      console.error("获取店铺分类失败:", error);
    }

    const response = await request.get("/api/admin/stores", { params });
    console.log("getMerchants API响应:", response);

    // 处理响应数据，确保店主信息和分类信息正确
    if (response.data && response.data.content) {
      response.data.content = response.data.content.map((item: any) => ({
        ...item,
        // 确保店主名称字段正确映射
        ownerName: item.ownerName || item.userName || "未知",
        // 映射分类名称
        category:
          item.categoryId && categories[item.categoryId]
            ? categories[item.categoryId]
            : item.category || `分类ID: ${item.categoryId || "未知"}`,
        // 其他字段映射...
        createTime: item.createdAt || item.createTime,
      }));
    }

    return response;
  } catch (error) {
    console.error("getMerchants API错误:", error);
    throw error;
  }
}

// 审核商家店铺
export async function reviewStore(
  storeId: string,
  status: string, // 这里的status可能是前端的'OPEN'或'SUSPENDED'
  reason?: string
) {
  console.log("调用reviewStore API，参数:", { storeId, status, reason });
  // 根据API文档，/api/admin/stores/{id}/status 接口的 AuditDTO 只接受 'APPROVED' 和 'SUSPENDED'
  // 如果前端传入 'OPEN'，我们将其映射为 'APPROVED'
  const apiStatus = status === "OPEN" ? "APPROVED" : status;

  try {
    const response = await request.put(`/api/admin/stores/${storeId}/status`, {
      status: apiStatus,
      reason,
    });
    console.log("reviewStore API响应:", response);
    return response;
  } catch (error) {
    console.error("reviewStore API错误:", error);
    throw error;
  }
}

// ==================== 管理员商品管理 ====================

// 获取商品列表
export async function getProducts(params?: any) {
  console.log("调用getProducts API，参数:", params);
  try {
    // 获取商品分类信息
    let foodCategories: Record<string, Record<string, string>> = {};

    // 如果有storeId参数，只获取该店铺的分类
    if (params && params.storeId) {
      try {
        // getCategories返回的是Promise<FoodCategoryVO[]>
        const categories = await getCategories(params.storeId);
        if (categories && Array.isArray(categories)) {
          foodCategories[params.storeId] = {};
          categories.forEach((cat: any) => {
            if (cat.id && cat.name) {
              foodCategories[params.storeId][cat.id] = cat.name;
            }
          });
        }
      } catch (error) {
        console.error(`获取店铺 ${params.storeId} 的商品分类失败:`, error);
      }
    }

    const response = await request.get("/api/admin/foods", { params });
    console.log("getProducts API响应:", response);

    // 处理响应数据，确保店铺信息和分类信息正确
    if (response.data && response.data.content) {
      response.data.content = response.data.content.map((item: any) => {
        // 尝试获取分类名称
        let categoryName = item.category || "";
        if (item.storeId && item.categoryId && foodCategories[item.storeId]) {
          categoryName =
            foodCategories[item.storeId][item.categoryId] || categoryName;
        }

        return {
          ...item,
          // 确保店铺名称字段正确映射
          storeName: item.storeName || "未知店铺",
          // 确保分类名称正确映射
          category: categoryName || `分类ID: ${item.categoryId || "未知"}`,
          // 其他字段映射
          createTime: item.createdAt || item.createTime,
        };
      });
    }

    return response;
  } catch (error) {
    console.error("getProducts API错误:", error);
    throw error;
  }
}

// 审核/下架商品
export async function reviewProduct(
  productId: string,
  status: string,
  reason?: string
) {
  console.log("调用reviewProduct API，参数:", { productId, status, reason });
  try {
    const response = await request.put(`/api/admin/foods/${productId}/status`, {
      status,
      reason: reason || "",
    });
    console.log("reviewProduct API响应:", response);
    return response;
  } catch (error: any) {
    console.error(
      "reviewProduct API错误:",
      error.response?.data || error.message || error
    );
    throw error;
  }
}

// ==================== 管理员订单管理 ====================

// 获取所有订单
export async function getAllOrders(params?: any) {
  console.log("调用getAllOrders API，参数:", params);
  try {
    const response = await request.get("/api/admin/orders", { params });
    console.log("getAllOrders API响应:", response);
    return response;
  } catch (error) {
    console.error("getAllOrders API错误:", error);
    throw error;
  }
}

// ==================== 管理员评价管理 ====================

// 获取评价列表
export async function getReviews(params?: any) {
  console.log("调用getReviews API，参数:", params);
  try {
    const response = await request.get("/api/admin/reviews", { params });
    console.log("getReviews API响应:", response);
    return response;
  } catch (error) {
    console.error("getReviews API错误:", error);
    throw error;
  }
}

// 删除评价
export async function deleteReview(reviewId: string) {
  return request.delete(`/api/admin/reviews/${reviewId}`);
}

// ==================== 管理员平台统计 ====================

// 获取平台统计数据
export async function getPlatformStats(params?: any) {
  console.log("调用getPlatformStats API，参数:", params);
  try {
    const response = await request.get("/api/admin/statistics", { params });
    console.log("getPlatformStats API响应:", response);
    return response;
  } catch (error) {
    console.error("getPlatformStats API错误:", error);
    throw error;
  }
}

// ==================== 管理员骑手管理 ====================

// 获取骑手列表
export async function getRiders(params?: any) {
  console.log("调用getRiders API，参数:", params);
  try {
    const response = await request.get("/api/admin/riders", { params });
    console.log("getRiders API响应:", response);
    return response;
  } catch (error) {
    console.error("getRiders API错误:", error);
    throw error;
  }
}

// 更改骑手状态
export async function updateRiderStatus(
  riderId: string,
  status: string,
  reason?: string
) {
  console.log("调用updateRiderStatus API，参数:", { riderId, status, reason });
  try {
    const response = await request.put(`/api/admin/riders/${riderId}/status`, {
      status,
      reason: reason || (status === "SUSPENDED" ? "管理员禁用" : ""),
    });
    console.log("updateRiderStatus API响应:", response);
    return response;
  } catch (error) {
    console.error("updateRiderStatus API错误:", error);
    throw error;
  }
}
